<template>
  <el-form :inline="true" :model="where" class="ele-form-search">
    <div class="search-line" v-for="(line, index) in formSearch" :key="index" v-show="(show || line.len !== line.hide)">
      <div v-for="(item, idx) in line.list" :key="idx" style="display: inline-block">
        <el-form-item
            v-if="show || !item.hide"
            :class="[item.formWidth ? 'formItemWidth' +item.formWidth : '' ,'type' in item ? '' : 'none']"
        >
          {{ void (width = (item.width || 140) + 'px') }}
          <span v-if="item.labelName" style="font-size: 12px;">{{ item.labelName }}：</span>
          <template v-if="item.type === 'slot'">
            <slot :name="item.slotName"/>
          </template>
          <template v-if="item.type === 'tag'">
            <el-tag
                :key="tagIndex"
                v-for="(tag, tagIndex) in where[item.field]"
                closable
                :disable-transitions="false"
                @close="removeTag(item.field, tagIndex)">
              {{ tag }}
            </el-tag>
            <el-input
                style="width: 130px;margin-left: 10px;"
                v-model="tagInput"
                placeholder="输入后点+号"
                ref="saveTagInput">
              <el-button slot="append" icon="el-icon-plus" @click="saveTag(item.field)"></el-button>
            </el-input>
          </template>
          <template v-if="item.type === 'select'">
            <el-select :style="{width: width}" @change="reload" v-model="where[item.field]"
                       :placeholder="'请选择'+item.name">
              <el-option v-for="item in item.list" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </template>
          <template v-else-if="item.type === 'input'">
            <el-input clearable @clear="reload" :style="{width: width}" v-model="where[item.field]"
                      :placeholder="item.name"/>
          </template>
          <template v-else-if="item.type === 'change'">
            <el-radio-group v-model="where[item.field]" size="mini" @change="reload">
              <el-radio-button v-for="item in item.list" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </template>
          <template v-else-if="item.type === 'filterable'">
            <filterable-select v-model="where[item.field]" :type="item.category" :name="item.name"
                               :style="{width: width}"/>
          </template>
          <template v-else-if="item.type === 'daterange' || item.type === 'datetimerange'">
            <el-date-picker
                :class="item.type === 'daterange' ? 'search-date-editor' : 'search-date-editor-time'"
                v-model="where[item.field]"
                :type="item.type"
                :format="'yyyy-MM-dd'+(item.type === 'daterange' ? '' : ' HH:mm:ss')"
                :value-format="'yyyy-MM-dd'+(item.type === 'daterange' ? '' : ' HH:mm:ss')"
                unlink-panels
                range-separator="至"
                :default-time="['00:00:00', '23:59:59']"
                :start-placeholder="('name' in item ? item.name + '开始日期' : '开始日期')"
                :end-placeholder="('name' in item ? item.name + '结束日期' : '结束日期')"
                :picker-options="pickerOptions">
            </el-date-picker>
          </template>
          <template v-else-if="item.type === 'linkage'">
            <el-select
                :style="{width: width}" @change="changeLinkage(item)"
                v-model="where[item.field]"
                :placeholder="'请选择'+item.name">
              <el-option v-for="item in item.list" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
            <template v-if="item.field in linkage && linkage[item.field].length">
              <el-select :style="{width: (item.subSetting.width || 140)+'px'}" style="margin-left: 10px"
                         v-model="where[item.subSetting.field]" :placeholder="'请选择'+item.subSetting.name">
                <el-option v-for="item in linkage[item.field]" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </template>
          </template>
        </el-form-item>
      </div>
      <template v-if="Number(index) === 1">
        <slot name="button-before"/>
        <template v-if="settings.length && showSearchButton">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" class="ele-btn-icon" @click="reload">
              查询
            </el-button>
            <el-button type="primary" icon="el-icon-refresh" class="ele-btn-icon" @click="clearReload" v-if="refresh">
              重置
            </el-button>
          </el-form-item>
        </template>
        <slot name="button-after"/>
        <el-form-item v-if="settings.length && showSearchButton && showButton">
          <el-link
              type="primary" :underline="false"
              :icon="show ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              @click="show = !show">
            {{ show ? '收起' : '更多' }}
          </el-link>
        </el-form-item>
      </template>
    </div>
    <div>
      <slot name="search-after"></slot>
    </div>
  </el-form>
</template>

<script>
import FilterableSelect from '@/components/plugIn/filterable-select'

export default {
  name: 'query-search',
  components: { FilterableSelect },
  props: {
    // 配置参数
    settings: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 默认条件
    query: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 显示重置按钮
    refresh: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    query: {
      handler: function (value) {
        this.where = Object.assign({}, value, {})
      },
      deep: true
    }
  },
  mounted () {
    this.reloadSearchForm()
  },
  data () {
    return {
      tagInput: '',
      where: {},
      linkage: {}, // 联级
      show: false,
      showButton: false,
      showSearchButton: true, // 是否显示搜索按钮
      formSearch: {},
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            const end = new Date(new Date().setHours(23, 59, 59, 999))
            const start = new Date(new Date().setHours(0, 0, 0))
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const end = new Date(new Date().setHours(23, 59, 59, 999))
            const start = new Date(new Date().setHours(0, 0, 0))
            start.setTime(start.getTime() - (3600 * 1000 * 24))
            end.setTime(end.getTime() - (3600 * 1000 * 24))
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  methods: {
    removeTag (field, tagIndex) {
      this.where[field].splice(tagIndex, 1)
    },
    saveTag (field) {
      if (!this.tagInput) {
        return
      }
      if (!(field in this.where)) {
        this.where[field] = [this.tagInput]
      } else if (!this.where[field].includes(this.tagInput)) {
        this.where[field].push(this.tagInput)
      }
      this.where = Object.assign({}, this.where)
      this.tagInput = ''
    },
    setQuery (field, value) {
      this.$set(this.where, field, value)
    },
    getQuery () {
      return Object.assign({}, this.where)
    },
    reloadSearchForm (query = {}) {
      this.where = Object.assign({}, this.query, query, {})
      this.showSearchButton = false
      let formSearch = {}
      for (let i = 0; i < this.settings.length; i++) {
        let line = this.settings[i]?.line || 1
        if (!(line in formSearch)) {
          formSearch[line] = {
            list: [],
            hide: 0,
            len: 0,
          }
        }
        formSearch[line].list.push(this.settings[i])
        formSearch[line].len += 1
        if ('type' in this.settings[i]) {
          this.showSearchButton = true
        }
        if ('hide' in this.settings[i]) {
          formSearch[line].hide += 1
          this.showButton = true
        }
      }
      this.formSearch = formSearch
    },
    reload () {
      this.$emit('reload', this.where)
    },
    clearReload () {
      this.linkage = {}
      this.where = Object.assign({}, this.query, {})
      this.$emit('reload', this.where)
    },
    changeLinkage (item) {
      delete this.linkage[item.field]
      delete this.where[item.subSetting.field]
      for (let i = 0; i < this.settings.length; i++) {
        let data = this.settings[i]
        if ('field' in data && data.field === item.field) {
          for (let v = 0; v < data.list.length; v++) {
            let line = data.list[v]
            if (line.value === this.where[item.field] && 'children' in line && line.children.length) {
              this.$set(this.linkage, item.field, line.children)
            }
          }
        }
      }
    }
  }
}
</script>

<style>
.search-line:last-of-type {
  display: inline-block;
}

.el-radio-button--mini .el-radio-button__inner {
  padding: 7px 8px;
}

.ele-form-search.el-form--inline .el-form-item:not(.ele-form-actions) .el-form-item__content {
  max-width: none;
}
</style>
